<template>
  <div class="app-container">
    <!-- 顶部导航标签 -->
    <div class="nav-tabs">
      <div class="nav-tab" 
        v-for="tab in tabs" 
        :key="tab.key"
        :class="{ active: currentTab === tab.key }"
        @click="handleTabClick(tab.key)">
        {{ tab.name }}
      </div>
    </div>

    <!-- 策略列表内容 -->
    <div v-show="currentTab === 'list'" class="content-wrapper">
      <div class="filter-section">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索策略名称、ID、标签..."
            prefix-icon="el-icon-search"
            clearable
          />
        </div>
        <div class="filter-box">
          <el-dropdown trigger="click" @command="handleStatusChange">
            <el-button plain>
              {{ currentStatus || '所有状态' }} <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="">所有状态</el-dropdown-item>
              <el-dropdown-item command="running">运行中</el-dropdown-item>
              <el-dropdown-item command="stopped">已停止</el-dropdown-item>
              <el-dropdown-item command="paused">已暂停</el-dropdown-item>
              <el-dropdown-item command="error">出错</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown trigger="click" @command="handleMarketChange">
            <el-button plain>
              {{ currentMarket || '所有市场' }} <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="">所有市场</el-dropdown-item>
              <el-dropdown-item command="binance_spot">Binance 现货</el-dropdown-item>
              <el-dropdown-item command="binance_futures">Binance 合约</el-dropdown-item>
              <el-dropdown-item command="okex">OKEx</el-dropdown-item>
              <el-dropdown-item command="huobi">Huobi</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown trigger="click" @command="handleTypeChange">
            <el-button plain>
              {{ currentType || '所有类型' }} <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="">所有类型</el-dropdown-item>
              <el-dropdown-item command="arbitrage">套利策略</el-dropdown-item>
              <el-dropdown-item command="trend">趋势策略</el-dropdown-item>
              <el-dropdown-item command="grid">网格策略</el-dropdown-item>
              <el-dropdown-item command="market_making">做市策略</el-dropdown-item>
              <el-dropdown-item command="hedge">对冲策略</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button plain @click="handleMoreFilters">更多筛选</el-button>
          <el-button plain @click="clearFilters">清除筛选</el-button>
          <el-button type="primary" icon="el-icon-plus" class="create-btn" @click="handleTabClick('create')">
            创建策略
          </el-button>
        </div>
      </div>

      <!-- 策略列表 -->
      <div class="strategy-list">
        <div class="strategy-card" v-for="strategy in filteredStrategies" :key="strategy.id">
          <div class="strategy-header">
            <div class="strategy-name">
              <el-checkbox 
                v-model="strategy.selected" 
                @change="handleStrategySelect(strategy)"
              ></el-checkbox>
              <span class="status-dot" :class="'status-' + strategy.status"></span>
              {{ strategy.name }}
            </div>
            <div class="strategy-actions">
              <el-button 
                size="small" 
                :type="strategy.status === 'running' ? 'warning' : 'success'"
                @click="handleStatusToggle(strategy)">
                {{ strategy.status === 'running' ? '暂停' : '启动' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleStop(strategy)">停止</el-button>
              <el-button size="small" plain @click="handleEdit(strategy)">编辑</el-button>
            </div>
          </div>
          <div class="strategy-info">
            <div class="info-item">
              <span class="label">ID:</span>
              <span class="value">{{ strategy.id }}</span>
            </div>
            <div class="info-item">
              <span class="label">市场:</span>
              <span class="value">{{ strategy.market }}</span>
            </div>
            <div class="info-item">
              <span class="label">交易对:</span>
              <span class="value">{{ strategy.pairs }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态:</span>
              <span class="value">
                <el-tag :type="getStatusType(strategy.status)" size="small">
                  {{ getStatusText(strategy.status) }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="label">{{ strategy.status === 'running' ? '运行时间:' : '最后运行:' }}</span>
              <span class="value">{{ strategy.runtime }}</span>
            </div>
          </div>
          <div class="strategy-metrics">
            <div class="metric-item">
              <div class="metric-value" :class="strategy.profit >= 0 ? 'positive' : 'negative'">
                {{ strategy.profit >= 0 ? '+' : '' }}{{ strategy.profit }}%
              </div>
              <div class="metric-label">收益率</div>
            </div>
            <div class="metric-item">
              <div class="metric-value">{{ strategy.trades }}</div>
              <div class="metric-label">交易次数</div>
            </div>
            <div class="metric-item">
              <div class="metric-value">{{ strategy.winRate }}%</div>
              <div class="metric-label">胜率</div>
            </div>
            <div class="metric-item">
              <div class="metric-value">{{ strategy.sharpe }}</div>
              <div class="metric-label">夏普比率</div>
            </div>
            <div class="metric-item">
              <div class="metric-value negative">{{ strategy.drawdown }}%</div>
              <div class="metric-label">最大回撤</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total">
        </el-pagination>
      </div>

      <!-- 批量操作浮动栏 -->
      <transition name="slide-up">
        <div class="batch-operations-bar" v-if="hasSelection">
          <div class="batch-operations-content">
            <div class="operation-hint">
              <el-checkbox 
                v-model="isAllSelected"
                @change="handleSelectAll"
              >全选</el-checkbox>
              <span class="selected-count">已选择 {{ selectedStrategies.length }} 个策略</span>
            </div>
            <div class="operation-buttons">
              <el-button type="success" size="small" @click="handleBatchStart">
                <i class="el-icon-video-play"></i> 批量启动
              </el-button>
              <el-button type="warning" size="small" @click="handleBatchPause">
                <i class="el-icon-video-pause"></i> 批量暂停
              </el-button>
              <el-button type="danger" size="small" @click="handleBatchStop">
                <i class="el-icon-video-pause"></i> 批量停止
              </el-button>
              <el-button type="primary" plain size="small" @click="handleBatchExport">
                <i class="el-icon-download"></i> 批量导出
              </el-button>
              <el-button type="info" plain size="small" @click="handleBatchBackup">
                <i class="el-icon-document-copy"></i> 批量备份
              </el-button>
              <el-button type="text" @click="clearSelection">
                <i class="el-icon-close"></i> 取消选择
              </el-button>
            </div>
          </div>
        </div>
      </transition>
    </div>

    <!-- 创建策略内容 -->
    <div v-show="currentTab === 'create'" class="content-wrapper">
      <create-strategy-form 
        @saved="handleStrategySaved"
        @cancel="handleStrategyCancel"
      />
    </div>

    <!-- 性能分析内容 -->
    <div v-show="currentTab === 'analysis'" class="content-wrapper">
      <strategy-analysis />
    </div>

    <!-- 参数优化内容 -->
    <div v-show="currentTab === 'optimization'" class="content-wrapper">
      <strategy-optimization />
    </div>

    <!-- 版本控制内容 -->
    <div v-show="currentTab === 'version'" class="content-wrapper">
      <version-control 
        :current-strategy="currentStrategy"
        :strategies="strategies"
        @view="handleViewVersion"
        @restore="handleRestoreVersion"
      />
    </div>

    <!-- 编辑策略弹窗 -->
    <el-dialog
      title="编辑策略"
      :visible.sync="editDialogVisible"
      width="80%"
      :before-close="handleEditDialogClose"
      class="edit-strategy-dialog"
    >
      <create-strategy-form 
        ref="editForm"
        :is-edit="true"
        :strategy-data="currentEditStrategy"
        @saved="handleEditSaved"
        @cancel="handleEditDialogClose"
      />
    </el-dialog>
  </div>
</template>

<script>
import CreateStrategyForm from './components/create.vue'
import StrategyAnalysis from './components/analysis.vue'
import StrategyOptimization from './components/optimization.vue'
import VersionControl from './components/version-control.vue'

export default {
  name: 'StrategyList',
  components: {
    CreateStrategyForm,
    StrategyAnalysis,
    StrategyOptimization,
    VersionControl
  },
  data() {
    return {
      // 顶部标签页
      tabs: [
        { key: 'list', name: '策略列表' },
        { key: 'create', name: '创建策略' },
        { key: 'analysis', name: '性能分析' },
        { key: 'optimization', name: '参数优化' },
        { key: 'version', name: '版本控制' }
      ],
      currentTab: 'list',
      
      // 搜索和筛选
      searchQuery: '',
      currentStatus: '',
      currentMarket: '',
      currentType: '',
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 30,

      // 策略列表数据
      strategies: [
        {
          id: 'STRAT-9845',
          name: 'BTC-ETH 多市场套利策略',
          status: 'running',
          market: 'Binance, OKEx',
          pairs: 'BTC/USDT, ETH/USDT',
          runtime: '5天12小时',
          profit: 5.37,
          trades: 68,
          winRate: 72.1,
          sharpe: 2.45,
          drawdown: -1.8,
          type: 'arbitrage'
        },
        {
          id: 'STRAT-9752',
          name: 'ETH-USDT 趋势跟踪策略',
          status: 'stopped',
          market: 'Binance',
          pairs: 'ETH/USDT',
          runtime: '2天前',
          profit: 12.64,
          trades: 145,
          winRate: 68.3,
          sharpe: 1.87,
          drawdown: -5.3,
          type: 'trend'
        },
        {
          id: 'STRAT-9681',
          name: 'BTC-SOL-AVAX 轮动策略',
          status: 'paused',
          market: 'Binance, OKEx',
          pairs: 'BTC/USDT, SOL/USDT, AVAX/USDT',
          runtime: '6小时前',
          profit: 21.35,
          trades: 98,
          winRate: 65.3,
          sharpe: 2.12,
          drawdown: -8.7,
          type: 'trend'
        }
      ],
      selectedStrategies: [],
      isAllSelected: false,
      currentStrategy: '',
      showVersionControl: false,
      editDialogVisible: false,
      currentEditStrategy: null
    }
  },
  computed: {
    filteredStrategies() {
      return this.strategies.filter(strategy => {
        const matchQuery = !this.searchQuery || 
          strategy.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
          strategy.id.toLowerCase().includes(this.searchQuery.toLowerCase())
        
        const matchStatus = !this.currentStatus || 
          strategy.status === this.currentStatus
        
        const matchMarket = !this.currentMarket || 
          strategy.market.toLowerCase().includes(this.currentMarket.replace('_', ' '))
        
        const matchType = !this.currentType || 
          strategy.type === this.currentType

        return matchQuery && matchStatus && matchMarket && matchType
      })
    },
    hasSelection() {
      return this.selectedStrategies.length > 0
    }
  },
  watch: {
    currentTab: {
      immediate: true,
      handler(val) {
        this.showVersionControl = val === 'version'
        if (val === 'version' && !this.currentStrategy) {
          // 如果没有选择策略，默认选择第一个
          this.currentStrategy = this.strategies[0]?.id
        }
      }
    }
  },
  methods: {
    handleTabClick(tab) {
      this.currentTab = tab
    },
    handleStatusChange(command) {
      this.currentStatus = command
    },
    handleMarketChange(command) {
      this.currentMarket = command
    },
    handleTypeChange(command) {
      this.currentType = command
    },
    handleMoreFilters() {
      // 实现更多筛选逻辑
    },
    clearFilters() {
      this.searchQuery = ''
      this.currentStatus = ''
      this.currentMarket = ''
      this.currentType = ''
    },
    handleStatusToggle(strategy) {
      if (strategy.status === 'running') {
        strategy.status = 'paused'
      } else {
        strategy.status = 'running'
      }
    },
    handleStop(strategy) {
      strategy.status = 'stopped'
    },
    handleEdit(strategy) {
      this.currentEditStrategy = { ...strategy }
      this.editDialogVisible = true
    },
    handleEditDialogClose() {
      this.editDialogVisible = false
      this.currentEditStrategy = null
    },
    handleEditSaved() {
      this.editDialogVisible = false
      this.currentEditStrategy = null
      this.loadStrategies()
      this.$message.success('策略编辑成功')
    },
    getStatusType(status) {
      const typeMap = {
        running: 'success',
        stopped: 'danger',
        paused: 'warning',
        error: 'danger'
      }
      return typeMap[status]
    },
    getStatusText(status) {
      const textMap = {
        running: '运行中',
        stopped: '已停止',
        paused: '已暂停',
        error: '出错'
      }
      return textMap[status]
    },
    handlePageChange(page) {
      this.currentPage = page
    },
    handleStrategySelect(strategy) {
      if (strategy.selected) {
        this.selectedStrategies.push(strategy);
      } else {
        const index = this.selectedStrategies.findIndex(s => s.id === strategy.id);
        if (index > -1) {
          this.selectedStrategies.splice(index, 1);
        }
      }
      // 更新全选状态
      this.isAllSelected = this.strategies.length === this.selectedStrategies.length;
    },
    handleSelectAll(value) {
      this.strategies.forEach(strategy => {
        strategy.selected = value;
      });
      this.selectedStrategies = value ? [...this.strategies] : [];
    },
    handleBatchStart() {
      this.$confirm('确认启动选中的策略吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedStrategies.forEach(strategy => {
          strategy.status = 'running'
        })
        this.$message.success('批量启动成功')
      })
    },
    handleBatchPause() {
      this.$confirm('确认暂停选中的策略吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedStrategies.forEach(strategy => {
          strategy.status = 'paused'
        })
        this.$message.success('批量暂停成功')
      })
    },
    handleBatchStop() {
      this.$confirm('确认停止选中的策略吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedStrategies.forEach(strategy => {
          strategy.status = 'stopped'
        })
        this.$message.success('批量停止成功')
      })
    },
    handleBatchExport() {
      this.$message.success('开始导出选中的策略')
      // 实现导出逻辑
    },
    handleBatchBackup() {
      this.$message.success('开始备份选中的策略')
      // 实现备份逻辑
    },
    clearSelection() {
      this.isAllSelected = false;
      this.selectedStrategies = [];
      this.strategies.forEach(strategy => {
        strategy.selected = false;
      });
    },
    handleStrategySaved() {
      this.currentTab = 'list'
      // 刷新策略列表
      this.loadStrategies()
    },
    handleStrategyCancel() {
      this.currentTab = 'list'
    },
    loadStrategies() {
      // 实现加载策略列表的逻辑
    },
    handleViewVersion(version) {
      console.log('View version:', version)
    },
    handleRestoreVersion(version) {
      console.log('Restore version:', version)
      this.loadStrategies()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f6f8fa;
  min-height: 100vh;
  width: 100%;
  position: relative;

  .nav-tabs {
    display: flex;
    background: #fff;
    border-radius: 4px;
    padding: 0 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .nav-tab {
      padding: 15px 20px;
      cursor: pointer;
      position: relative;
      color: #606266;
      font-size: 14px;
      transition: all 0.3s;

      &.active {
        color: #409EFF;
        font-weight: 500;

        &:after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 2px;
          background: #409EFF;
        }
      }

      &:hover:not(.active) {
        color: #409EFF;
      }
    }
  }

  .filter-section {
    margin-bottom: 20px;

    .search-box {
      margin-bottom: 15px;
    }

    .filter-box {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      position: relative;

      .el-button {
        min-width: 120px;
      }

      .create-btn {
        margin-left: auto;
      }
    }
  }

  .strategy-list {
    .strategy-card {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      margin-bottom: 15px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

      .strategy-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .strategy-name {
          font-size: 16px;
          font-weight: 500;
          display: flex;
          align-items: center;
        }

        .strategy-actions {
          display: flex;
          gap: 8px;
        }
      }

      .strategy-info {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        padding: 15px 0;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
        margin-bottom: 15px;

        .info-item {
          .label {
            color: #909399;
            margin-right: 8px;
          }
        }
      }

      .strategy-metrics {
        display: flex;
        justify-content: space-between;

        .metric-item {
          text-align: center;
          flex: 1;

          .metric-value {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 4px;

            &.positive {
              color: #67C23A;
            }

            &.negative {
              color: #F56C6C;
            }
          }

          .metric-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }

  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
    display: inline-block;

    &.status-running {
      background-color: #67C23A;
    }

    &.status-stopped {
      background-color: #F56C6C;
    }

    &.status-paused {
      background-color: #E6A23C;
    }

    &.status-error {
      background-color: #F56C6C;
      animation: blink 1s infinite;
    }
  }

  .pagination-wrapper {
    text-align: center;
    margin-top: 20px;
  }

  .content-wrapper {
    max-width: 1280px;
    margin: 0 auto;
    padding-bottom: 70px;
  }

  .batch-operations-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    border-top: 1px solid #ebeef5;

    .batch-operations-content {
      max-width: 1280px;
      margin: 0 auto;
      padding: 12px 20px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .operation-hint {
        display: flex;
        align-items: center;
        gap: 12px;
        white-space: nowrap;
        margin-right: 60px;

        .el-checkbox {
          margin-right: 0;
        }

        .selected-count {
          color: #606266;
          font-size: 14px;
        }
      }

      .operation-buttons {
        display: flex;
        gap: 8px;
        align-items: center;

        .el-button {
          padding: 8px 12px;
          
          i {
            margin-right: 4px;
          }

          &.el-button--text {
            padding: 8px;
            color: #909399;

            &:hover {
              color: #409EFF;
            }
          }
        }
      }
    }
  }

  // 添加上滑动画
  .slide-up-enter-active,
  .slide-up-leave-active {
    transition: transform 0.25s ease-out;
  }

  .slide-up-enter,
  .slide-up-leave-to {
    transform: translateY(100%);
  }

  .placeholder {
    text-align: center;
    padding: 100px 0;
    color: #909399;
    font-size: 14px;
  }

  .edit-strategy-dialog {
    ::v-deep .el-dialog__body {
      padding: 0;
    }
  }
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style> 